package com.itrip.listener;

import com.itrip.service.OrderService;
import com.itrip.service.TempStoreService;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Resource
    private OrderService orderService;

    @Resource
    private TempStoreService tempStoreService;



    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
    @Override
    public void onMessage(Message message, byte[] pattern) {
        //获取失效的key
        String expiredKey = message.toString();



        if(expiredKey.startsWith("order:")){
            //订单的key-获取订单ID  （order:219,1,1）
            String id = expiredKey.substring(expiredKey.indexOf(":")+1,expiredKey.indexOf(","));
            long orderId = Long.parseLong(id);

            //查询订单状态
            int status = orderService.getOrderStatus(orderId);
            if(status == 0){//未支付
                //修改订单状态-已失效
                int countOrder = orderService.updateOrderStatusInvalid(orderId);

                //获取扣减的库存
                String storeStr = expiredKey.substring(expiredKey.lastIndexOf(",")+1);
                int store = Integer.parseInt(storeStr);

                //获取房间ID
                String roomIdStr = expiredKey.substring(expiredKey.indexOf(",")+1, expiredKey.lastIndexOf(","));
                long roomId = Long.parseLong(roomIdStr);


                //恢复占用的库存
                int countStore = tempStoreService.addStoreRevert(roomId, store);
            }
        }
    }
}
